package com.aij.starter.jna;

import com.sun.jna.Callback;
import com.sun.jna.Library;
import com.aij.starter.event.ChatGlmEventHandler;
import com.aij.starter.utils.NativeUtils;

/**
 * 加载chatglm动态库
 * @author aij
 */
public class ChatGlm {

    static ChatGlmLibrary CHATGLM;
	static {
		try {
			System.setProperty("jna.encoding", "UTF-8");
			CHATGLM = (ChatGlmLibrary)NativeUtils.loadFromJar("chatglm", ChatGlmLibrary.class);
		} catch (Exception e) {
			System.out.println("ChatGlm Load: " + e.getMessage() + "\n" + e.getStackTrace());
		}
	}
	
	public interface ChatGlmLibrary extends Library {
		
		void chatglm_init(String path_model);

        void chatglm_free();

        public interface OnNewWord extends Callback {
            void callback(String text);
        }
        void chatglm_chat(String word, OnNewWord cb);
	}

    public static void Initialize(String model)
    {
        try
        {
        	CHATGLM.chatglm_init(model);
        }
        catch (Exception e)
        {
			System.out.println("ChatGlm Initialize: " + model + "\n" + e.getMessage() + "\n" + e.getStackTrace());
        }
    }

    public static void Run(String word)
    {
        try
        {
        	CHATGLM.chatglm_chat(word, new ChatGlmEventHandler());
        }
        catch (Exception e)
        {
			System.out.println("ChatGlm Run: " + e.getMessage() + "\n" + e.getStackTrace());
        }
    }

    public static void Destroy()
    {
        CHATGLM.chatglm_free();
    }
 
	// Test Driver
	public static void main(String[] args) {
		//String url = ClassLoader.getSystemResource("models/ruoyi-ggml.bin").getPath();
		String url = "/Volumes/MACBOOK/macbook/Documents/cmake/chatglm.cpp/models/ruoyi-ggml.bin";
		//String url = "D:/Documents/cmake/chatglm.cpp/models/ruoyi-ggml.bin";
		ChatGlm.Initialize(url);  // Allocate an instance and invoke the native method
		ChatGlm.Run("你好");
		ChatGlm.Destroy();
	}
}
